const { src, dest, watch, series, parallel } = require('gulp');
const htmlmin = require('gulp-htmlmin')  // 压缩html
const cssforSass = require('gulp-sass'); // 转译 sass  css
const minicss = require('gulp-csso'); // 压缩
const babel = require('gulp-babel')   // 转译es6
const concat = require('gulp-concat')   // 拼接
const imagemin = require('gulp-imagemin') //压缩处理图片
const uglify = require('gulp-uglify'); // 压缩js
const webserver = require('gulp-webserver'); // 起服务 （读文件，写接口）
// const inject = require('gulp-inject');
const bodyParser = require('body-parser')
const rev = require('gulp-rev') // 添加md5后缀

const path = require('path')
const url = require('url')

// 处理html gulp-htmlmin
function html() {
  return src('src/index.html')
    .pipe(htmlmin({
      collapseWhitespace: true, // //压缩HTML
      minifyJS: true,  //压缩页面JS
      minifyCSS: true  //压缩页面CSS
    }))
    .pipe(dest('dist/')) // 我把处理后的html输出到dist
}

// 处理css (压缩  转译scss)
function sass() {
  return src('src/css/*.scss')
    .pipe(cssforSass()) // 转译为css
    .pipe(concat('./style.css'))
    .pipe(minicss())
    .pipe(rev())
    .pipe(dest('dist/css'))
}

// 处理js (babel转译 合并js)
function js() {
  return src('src/js/*.js')
    .pipe(babel({
      presets: ['@babel/env']
    }))   // 将es6转译为es5代码
    .pipe(concat('app.js'))
    .pipe(uglify())
    .pipe(rev())
    .pipe(dest('dist/js'))
}

// 处理图片
function image() {
  return src('src/img/*.(png|jpg|jpeg)')
    .pipe(imagemin({
      progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
    }))
    .pipe(dest('./dist/img'));
}

function server() {
  return src('src')
    .pipe(webserver({
      livereload: true, // 热更新
      // directoryListing: true,
      // open: true, // 自动打开页面
      port: 3000,
      middleware: [
        bodyParser.urlencoded(),
        bodyParser.json(),
        (req, res, next) => {
          //req:发送的请求
          //res:需要接受
          //next:指向下一步操作的指针

          const requestUrl = url.parse(req.url, true)
          const pathname = requestUrl.pathname;
          const params = requestUrl.query;
          const method = req.method;
          // res.setHeader('Content-Type', 'application/json');
          if (method === 'GET' && pathname === '/api/login') {
            res.end(`
            我是接口
              requestUrl: ${JSON.stringify(requestUrl)}; \n
              pathname: ${pathname}; \n
              params: ${JSON.stringify(params)}; \n
              method: ${method}; \n
          `)
            return;
          }
          if (method === 'POST' && pathname === '/api/login') {
            console.log(req.body, 'body')
            res.end(`
            我是接口
              requestUrl: ${JSON.stringify(requestUrl)} \n;
              pathname: ${pathname} \n;
              params: ${JSON.stringify(params)} \n;
              method: ${method} \n;
          `)
            return;
          }
          if (method === 'GET' && pathname === '/api/register') {
            res.end('登陆接口')
            console.log('register')
            return;
          }
          next()
        }]
    }));
}

function watchFile() {
  watch(['./src/css/*.scss'], series(sass))
  watch(['./src/js/*.js'], series(js))
  watch(['./src/img/*.png'], series(image))
  watch(['./src/index.html'], series(html))
}


// module.exports = {
//   html,
//   sass,
//   js,
//   image
// }

// exports.server = server;

// 合并执行  npx gulp 执行了所有的任务
exports.default = series(html, image, server, watchFile);
